package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.mapper.LogMapper;
import com.cskaoyan.mapper.PermissionMapper;
import com.cskaoyan.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * @author heyyon
 */
@Service
public class AdminAuthServiceImpl implements AdminAuthService{
    @Autowired
    LogMapper logMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Override
    public void login(boolean authenticated,String username) {
        Log log=new Log();
        try {
            String IP= InetAddress.getLocalHost().getHostAddress();
            log.setIp(IP);
            log.setAction("登录");
            if (authenticated) {
                log.setStatus(true);
            } else {
                log.setStatus(false);
                log.setResult("用户帐号或密码不正确");
            } 
            log.setAdmin(username);
            log.setType(1);
            logMapper.insertSelective(log);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void logout(String name) {
        Log log=new Log();//封装为Log对象，将数据insert进数据库log表
        String IP= null;
        try {
            IP = InetAddress.getLocalHost().getHostAddress();
            log.setStatus(true);
            log.setType(1);
            log.setAdmin(name);
            log.setIp(IP);
            log.setAction("注销");
            logMapper.insertSelective(log);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    @Override
    public UserInfo info(Integer[] roleIds) {
        List<String> roleList=new ArrayList<>();
        List<String> permList=new ArrayList<>();
        List<String> permApis=new ArrayList<>();
        for (Integer roleId : roleIds) {
            String role = roleMapper.selectRoleNameById(roleId);
            roleList.add(role);
            List<String> list = permissionMapper.selectPermByRoleId(roleId);
            permList.addAll(list);
        }
        //使用hashset去除重复元素
        HashSet<String> set = new HashSet<String>(permList);
        for (String perm : set) {
            String permApi = permissionMapper.selectPermApiByPerm(perm);
            permApis.add(permApi);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setRoles(roleList);
        userInfo.setPerms(permApis);
        return userInfo;
    }


}
